<template>
  <basic-container>
    <!-- <avue-crud :option="option"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               :before-open="beforeOpen"
               :cell-style="cellStyle"
               :row-style="rowStyle"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad"> -->
    <avue-crud :option="option"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               :before-open="beforeOpen"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad"
               @keydown.native="keydown($event)"
              >
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.dept_delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {add, getDept, getDeptTree, getList, remove, update} from "@/api/system/dept";
  import {mapGetters} from "vuex";
  import website from '@/config/website';

  export default {
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入城市名称'));
        } else {
          this.form.deptName = value.replace(/[^\u4E00-\u9FA5]/g, '')
          callback();
        }
      };
      var fullNamePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入城市全称'));
        } else {
          this.form.fullName = value.replace(/\s+/g, '')
          callback();
        }
      };
      return {
        form: {},
        selectionList: [],
        query: {},
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          menuWidth: 150,
          tip: false,
          tree: true,
          border: true,
          index: true,
          columnBtn: false, // 列显隐按钮
          refreshBtn: false, // 刷新按钮
          searchBtn: false, // 搜索显隐按钮（当 column 中有搜索的属性，或则 searchsolt 为 true 时自定义搜索启动起作用）
          selection: true,
          viewBtn: true,
          column: [
            {
              label: "城市名称",
              prop: "deptName",
              search: true,
              // rules: [{
              //   required: true,
              //   message: "请输入城市名称",
              //   trigger: "blur"
              // }]
              rules: [{
                required: true,
                validator: validatePass,
                trigger: 'change'
              }]
            },
            {
              label: "所属租户",
              prop: "tenantId",
              type: "tree",
              dicUrl: "/api/xmbz-system/tenant/select",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: website.tenantMode,
              span: 24,
              props: {
                label: "tenantName",
                value: "tenantId"
              },
              // hide: !website.tenantMode,
              // search: website.tenantMode,
              hide: true,
              search: false,
              rules: [{
                required: true,
                message: "请输入所属租户",
                trigger: "click"
              }]
            },
            {
              label: "城市全称",
              prop: "fullName",
              search: true,
              rules: [{
                required: true,
                validator: fullNamePass,
                trigger: 'change'
              }]
            },
            {
              label: "上级城市",
              prop: "parentId",
              dicData: [],
              type: "tree",
              hide: true,
              width: 20,
              props: {
                label: "title"
              },
              rules: [{
                required: true,
                message: "请选择上级城市",
                trigger: "click"
              }]
            },

            {
              label: "排序",
              prop: "sort",
              type: "number",
              rules: [{
                required: true,
                message: "请输入排序",
                trigger: "blur"
              }]
            },

            {
              label: "备注",
              prop: "remark",
              span: 24,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.dept_add, false),
          viewBtn: this.vaildData(this.permission.dept_view, false),
          delBtn: this.vaildData(this.permission.dept_delete, false),
          editBtn: this.vaildData(this.permission.dept_edit, false),
          // addBtn: false,
          // delBtn: false,
          // editBtn: false
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, loading, done) {
        let cityArray = []
        let regionArray = []
        getDeptTree().then(res => {
          const result = res.data.data
          // console.log('result',result)
          result.forEach(item => {
            item.children.forEach((childrenitem,childrenindex) => {
              cityArray.push(childrenitem.title)
              if (item.children[childrenindex].children !== undefined) {
                item.children[childrenindex].children.forEach(regionitem => {
                  regionArray.push(regionitem.title)
                  // console.log('威威',regionitem)
                })
              }
            })
          })
          // console.log('item',cityArray,'this',regionArray)
          if(this.form.deptName == this.form.$parentId) {
            this.$message({
              message: '城市名称与上级城市不能重名，请重新编辑',
              type: 'warning'
            });
            done()
          } else {
            // 若上级为第一层
            if(this.form.parentId == 1) {
              if (cityArray.indexOf(this.form.deptName) == -1) {
                // console.log(cityitem,'item')
                if (this.form.sort >= 0) {
                  add(row).then(() => {
                    loading();
                    this.onLoad(this.page);
                    this.$message({
                      type: "success",
                      message: "操作成功!"
                    });
                  }, error => {
                    done();
                    console.log(error);
                  });
                } else {
                  this.$message.warning("排序不能为负数，请重新编辑");
                  done();
                }
              } else {
                this.$message({
                  message: '同层级已有相同的城市名称，请重新编辑',
                  type: 'warning'
                });
                done()
              }
            } else if (cityArray.indexOf(this.form.$parentId) > -1) {
              // console.log('this.form.$parentId',this.form.$parentId)
              let childrenArray = []
              getDeptTree().then(res => {
                res.data.data.forEach(item => {
                  item.children.forEach((childrenitem,childrenindex) => {
                    if (item.children[childrenindex].children !== undefined) {
                      if(this.form.$parentId == item.children[childrenindex].title) {
                        item.children[childrenindex].children.forEach(regionitem => {
                          childrenArray.push(regionitem.title)
                        })
                      }
                    }
                  })
                })
                if (childrenArray.indexOf(this.form.deptName) == -1) {
                  // console.log(cityitem,'item')
                  if (this.form.sort >= 0) {
                    add(row).then(() => {
                      loading();
                      this.onLoad(this.page);
                      this.$message({
                        type: "success",
                        message: "操作成功!"
                      });
                    }, error => {
                      done();
                      console.log(error);
                    });
                  } else {
                    this.$message.warning("排序不能为负数，请重新编辑");
                    done();
                  }
                } else {
                  this.$message({
                    message: '同层级已有相同的城市名称，请重新编辑',
                    type: 'warning'
                  });
                  done()
                }
              })
            } else if (regionArray.indexOf(this.form.$parentId) > -1) {
              // console.log('9999',this.form.$parentId)
              this.$message({
                message: '层级最多可叠加两层，请重新编辑',
                type: 'warning'
              });
              done()
            }
          }
        });
      },
      rowUpdate(row, index, loading, done) {
        // console.log('1111111',this.form)
        if (this.form.sort >= 0) {
          update(row).then(() => {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, error => {
            done();
            console.log(error);
          });
        } else {
          this.$message.warning("排序不能为负数，请重新编辑");
          done();
        }
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params) {
        this.query = params;
        this.onLoad(this.page, params);
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDept(this.form.id).then(res => {
            this.form = res.data.data;
            console.log('res.data.data',res.data.data)
          });
        }
        done();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        console.log('加载',this)
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          this.data = res.data.data;
          getDeptTree().then(res => {
            const data = res.data.data;
            const index = this.$refs.crud.findColumnIndex("parentId");
            this.option.column[index].dicData = data;
          });
        });
      },
      // 禁止输入空格
      keydown(event){
        if(event.keyCode == 32){
          event.returnValue = false
        }
      }
    }
  };
</script>

<style>
</style>
